package org.dandsoft.blackbox.laboratory.tests.streamer;

import org.dandsoft.blackbox.SignalId;

import java.util.*;
import java.io.*;

/**
 * @author Vilyuzhanin Denis (Fin)
 */
public class StreamReplacer {
    private Map<SignalId, Trigger> triggers = new Hashtable<SignalId, Trigger>();
    private Map<SignalId, LinkedList<Trigger>> firstSymbol = new Hashtable<SignalId, LinkedList<Trigger>>();
    private Set<Trigger> workTriggers = new HashSet<Trigger>();

    public void addTrigger(Trigger trigger) {
        if (!triggers.containsKey(trigger.getSignalId())) {
            triggers.put(trigger.getSignalId(), trigger);
            LinkedList<Trigger> triggers = firstSymbol.get(trigger.getSignalId());
            if (triggers != null) {
                triggers = new LinkedList<Trigger>();
                firstSymbol.put(trigger.getSignalId(), triggers);
            }
            triggers.add(trigger);
        }
    }

    public Map<SignalId, Integer> parse(SignalId signalId) {
        Map<SignalId, Integer> result = new Hashtable<SignalId, Integer>();
        for (Trigger trigger : workTriggers) {
            if (!trigger.parse(signalId)) {
                workTriggers.remove(trigger);
            } else {
                result.put(trigger.getSignalId(), trigger.getAccurancy());
            }
        }

        List<Trigger> newTriggers = firstSymbol.get(signalId);
        if (newTriggers != null) {
            for (Trigger trigger : newTriggers) {
                if (!workTriggers.contains(trigger)) {
                    trigger.reset();
                    if (trigger.parse(signalId)) {
                        result.put(trigger.getSignalId(), trigger.getAccurancy());
                    }
                }
            }
        }

        return result;
    }

    public void makeFromDictionary(InputStream in) throws IOException {
        int signalCounter = 0;
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, "windows-1251"));
        Map<String, SignalId> words = new Hashtable<String, SignalId>();
        String str;
        while ((str = reader.readLine()) != null) {
            for (int i = 1; i < str.length(); i++) {
                for (String s : parse(str, i)) {
                    if (!words.containsKey(s)) {
                        words.put(s, new SignalId(signalCounter));
                        signalCounter++;
                    }
                }
            }
        }

        for (Map.Entry<String, SignalId> entry : words.entrySet()) {
            Trigger trigger = new Trigger();
        }

    }

    private static List<String> parse(String str, int length) {
        List<String> words = new ArrayList<String>();
        for (int i = 0; i < str.length() - (length - 1); i++) {
            words.add(str.substring(i, i + length));
        }
        return words;
    }
}
